package com.srwl.mytx.widget;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.ForwardDonationRecordAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Donation;
import com.srwl.mytx.domain.Forward;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.DonationService;
import com.srwl.mytx.service.ForwardService;
import com.srwl.mytx.utils.PayUtils;
import com.srwl.mytx.utils.Utils;

import org.greenrobot.greendao.annotation.NotNull;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

;

public class ForwardDonationView extends LinearLayout {
    private static final String TAG = "DonationView";
    @BindView(R.id.btn_donation)
    Button btn_donation;
    @BindView(R.id.rv_donation)
    RecyclerView rv_donation;
    @BindView(R.id.tv_donation_count)
    TextView tv_donationCount;
    @BindView(R.id.tv_donation_amount)
    TextView tv_donationAmount;
    @BindView(R.id.tv_donation_balance)
    TextView tv_donationBalance;
    @BindView(R.id.rl_donation_balance)
    RelativeLayout rl_donationBalance;
    @BindView(R.id.tv_tips)
    TextView tv_tips;
    private ForwardDonationRecordAdapter donationRecordAdapter;
    private int donationPage = 1;
    private int donationSize = 5;
    private boolean hasNextPage = true;
    ArrayList<Donation> donationList = new ArrayList<>();
    private double donationAmount;
    private Integer donationCount;
    private Context context;
    private InteractionListener listener;
    private Forward forward;
    private double forwardAmount;

    public ForwardDonationView(Context context) {
        super(context);
        this.context = context;
        inflate(context, R.layout.donation_view, this);
        ButterKnife.bind(this);
    }

    public ForwardDonationView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        inflate(context, R.layout.donation_view, this);
        ButterKnife.bind(this);

    }


    public void setSize(int size) {
        donationSize = size;
    }

    public void init(@NotNull Forward forward, @NotNull InteractionListener listener) {
        donationList.clear();
        this.forward = forward;
        this.listener = listener;
        forwardAmount = forward.getAmount();
        if (forward.getDonationAmount() != null && forward.getDonationAmount() != 0) {
            donationAmount = forward.getDonationAmount();
        }
        tv_donationAmount.setText(Utils.moneyFormat(forwardAmount + donationAmount));
        rl_donationBalance.setVisibility(GONE);
        donationRecordAdapter = new ForwardDonationRecordAdapter(context, donationList);
        rv_donation.setLayoutManager(new LinearLayoutManager(context, RecyclerView.VERTICAL, false));
        rv_donation.setAdapter(donationRecordAdapter);
        rv_donation.setNestedScrollingEnabled(false);
        final User myUserInfo = UserProfileManager.getInstance().getLoginUserInfo();

        btn_donation.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                DonationDialog_1 donationDialog_1=new DonationDialog_1(TopicDetailsActivity.this);
//                donationDialog_1.show();
                if (myUserInfo.getUId().equals(forward.getTargetUser().getUId())) {
                    ConfirmDialog dialog = new ConfirmDialog(context, "提示", "不能给自己捐款哦");
                    dialog.show();
                    return;
                }

                NumberInputDialog donationDialog = NumberInputDialog.newInstance();
                donationDialog.setConfirmListener(new NumberInputDialog.ConfirmListener() {
                    @Override
                    public void confirm(final Double amount) {
                        Log.d(TAG, "confirm: forwardAmount:" + amount);
                        new PayUtils(context, amount, "捐赠 将从账户余额中扣除", new PayUtils.InteractionListener() {
                            @Override
                            public void onPrepareComplete(String payPassword) {
                                donation(amount, payPassword);
                            }
                        });

                    }
                });
                donationDialog.show(((FragmentActivity) context).getSupportFragmentManager(), "");
            }
        });
        tv_tips.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = "该类型的捐赠直接捐给最终的用户，不能拆回";
                ConfirmDialog dialog = new ConfirmDialog(context, "说明", content);
                dialog.show();
            }
        });

        loadData();
    }

    public void loadData() {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_LONG).show();
            return;
        }

        Map<String, Object> body = new HashMap<>();
        body.put("page", donationPage);
        body.put("size", donationSize);
        body.put("forwardId", forward.getfId());
        RetrofitManager.getInstance().createRequest(ForwardService.class)
                .queryForwardDonations(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (listener != null) {
                            listener.onLoadDonationComplete();
                        }
                        analysisResponse(response);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        if (listener != null) {
                            listener.onLoadDonationComplete();
                        }
                    }
                });

    }


    void analysisResponse(Response<CommonResult> response) {
        CommonResult result = response.body();
        if (!response.isSuccessful() || result == null) {
            Log.e(TAG, "onResponse: " + response.message());
            return;
        }
        if (result.isError()) {
            Log.e(TAG, "onResponse: " + result.getMsg());
            return;
        }
        JSONObject pageInfo = (JSONObject) result.getData();
        Log.d(TAG, "onResponse: 获取捐赠数据完成：" + pageInfo.toJSONString());

        donationCount = pageInfo.getInteger("total");
        tv_donationCount.setText(Utils.numberFormat(donationCount));

        hasNextPage = pageInfo.getBoolean("hasNextPage");
        if (!hasNextPage && listener != null) {
            listener.onHaveNotMoreData();
        }
        List<Donation> donations = pageInfo.getJSONArray("list").toJavaList(Donation.class);
        donationList.addAll(donations);
        donationRecordAdapter.notifyDataSetChanged();
        donationPage++;
    }

    public void showMoreDonationTextView(boolean hasNextPage) {


    }

    void donation(final double donationAmount, String payPassword) {

        final Donation donation = new Donation();
        donation.setAmount(donationAmount);
        Map<String, Object> body = new HashMap<>();
        body.put("donation", donation);
        if (!TextUtils.isEmpty(payPassword)) {
            body.put("payPassword", payPassword);
        }
        donation.setfId(forward.getfId());
        donation.settId(forward.getTargetUser().getuId());//直接捐给个人，需要设置 受款人id
        donationToPerson(donation, body);
    }

    private void donationToPerson(final Donation donation, Map<String, Object> body) {
        if (!Helper.getInstance().isNetworkConnected()){
            Toast.makeText(context,context.getString(R.string.network_anomalies),Toast.LENGTH_LONG).show();
            return;
        }
        listener.showProgressBar(true);
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .donationToPerson(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        listener.showProgressBar(false);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            listener.showToast(context.getString(R.string.system_busy));

                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {

                                case Constant.BALANCE_NOT_ENOUGH:
                                    listener.showToast(context.getString(R.string.balance_not_enough));
                                    break;
                                case Constant.NO_PAY_PASSWORD:
                                    //这样的情况，应该不会发生，因为发起请求前，做了判断
                                    listener.showToast("没有支付密码");

                                    break;
                                case Constant.NEED_SETUP_PAY_PASSWORD_BEFORE:
                                    //这样的情况，应该不会发生，因为发起请求前，做了判断
                                    listener.showToast("还没有设置支付密码");
                                    break;
                                case Constant.PAY_PASSWORD_ERROR:

                                    listener.showToast(getContext().getString(R.string.pay_password_error));

                                    break;
                                case Constant.GET_LOCK_FAIL:
                                case Constant.UNKNOWN_ERROR:
                                    listener.showToast(context.getString(R.string.system_busy));

                                    break;
                            }
                            return;
                        }
                        JSONObject data = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: 捐赠完成" + data.toJSONString());
                        double totalBalance = data.getDouble("balance");
                        //更新本地余额
                        UserProfileManager.getInstance().setUserBalance(totalBalance);
                        if (data.containsKey("historyDonation")) {
                            Donation historyDonation = data.getObject("historyDonation", Donation.class);
                            historyDonation.setTargetUser(UserProfileManager.getInstance().getLoginUserInfo());
                            showDonation(historyDonation);
                        } else {
                            String donationId = data.getString("donationId");
                            firstDonation(donationId, donation);
                        }
                        donationAmount += donation.getAmount();
                        tv_donationAmount.setText(Utils.moneyFormat(forwardAmount + donationAmount));
                        listener.onCommitDonationComplete();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        listener.showProgressBar(false);
                        listener.showToast(context.getString(R.string.system_busy));
                    }
                });
    }

    /**
     * 非第一次捐赠
     *
     * @param historyDonation
     */
    private void showDonation(Donation historyDonation) {

        boolean hasHistory = false;
        for (int i = 0; i < donationList.size(); i++) {
            Donation donation1 = donationList.get(i);
            if (TextUtils.equals(donation1.getId(), historyDonation.getId())) {
                donationList.remove(i);
                donationList.add(0, historyDonation);
                //判断历史捐赠是否处于第一个位置，如果不是，需要替换一下位置
                if (i != 0) {
                    donationRecordAdapter.notifyItemMoved(i, 0);
                }
                donationRecordAdapter.notifyItemChanged(0);
                hasHistory = true;
                break;
            }
        }
        if (!hasHistory) {
            donationList.add(0, historyDonation);
            donationRecordAdapter.notifyItemInserted(0);
        }
    }

    /**
     * 个人第一次对该主题捐赠
     *
     * @param donationId
     * @param donation
     */
    private void firstDonation(String donationId, Donation donation) {
        donation.setId(donationId);
        donation.setTargetUser(UserProfileManager.getInstance().getLoginUserInfo());
        donation.setHasPraise(false);
        donation.setCreated(new Date());
        donation.setStatus(Constant.DONATION_TYPE_TO_PERSON);

        donationCount++;
        tv_donationCount.setText(donationCount + "");
        if (donationList.size() == 0) {
            donationList.add(donation);
            donationRecordAdapter.notifyDataSetChanged();
        } else {
            donationList.add(0, donation);
            donationRecordAdapter.notifyItemInserted(0);
        }
    }

    public boolean isHasNextPage() {
        return hasNextPage;
    }

    public interface InteractionListener {

        void showToast(String message);

        void showProgressBar(boolean isShowProgressBar);

        void onLoadDonationComplete();

        void onHaveNotMoreData();

        void onCommitDonationComplete();
    }

}
